﻿#region Copyright(C) 2018 FI Ltd. All rights reserved.
// ==================================================================================================
// Copyright(C) 2018 FI Ltd. All rights reserved.
//
// SYSTEM NAME      : FI.Net Application Framework
// COMPONENT ID     : ApplicationContext
// COMPONENT DESC   : Session based contextual data sharing.
//
// CREATED DATE/BY  : 18 Aug 2018 / Tian Mi
//
// REVISION HISTORY :
// DATE/BY            SR#/CS/PM#/OTHERS      DESCRIPTION OF CHANGE
// ==================================================================================================
#endregion

using FI.Core.Properties;
using FI.Core.Utilities;
using System;
using System.Threading;

namespace FI.Core.ApplicationContexts
{
    /// <summary>
    /// This class control the scope of dependent context.
    /// </summary>
    public sealed class ApplicationContextScope: IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationContextScope"/> class.
        /// </summary>
        /// <param name="context">The dependent context cloned from the master application context.</param>
        public ApplicationContextScope(DependentApplicationContext context)
        {
            Guard.ArgumentNotNull(context, "context");
            if (context.MasterThread == Thread.CurrentThread)
            {
                throw new InvalidOperationException(Resources.ExceptionInvalidThreadToCreateContextScope);
            }
            ApplicationContext.Current.ContextLocator.AttachContext(context.Items, ContextAttachBehavior.Clear);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly")]
        public void Dispose()
        {
            ApplicationContext.Current.ContextLocator.Clear();
        }
    }
}